/**
 * Created by yesi on 15/5/13.
 */


var mongodb = require("mongodb"),
    assert = require('assert');
    mongoserver = new mongodb.Server("localhost", 9091 ),
    db = new mongodb.Db("gf", mongoserver),
    username = "gf",
    password = "gf",
    user_col = "user",
    cookie_col = "cookie";

function connect(callback){
    db.open(function(err, db) {
        if(err){return callback(err);}
        db.authenticate(username, password, function(err, result) {
            callback(err,db);
        });
    });
}

function findDocumentsByDb(obj ,col, db, callback) {
    var collection = db.collection(col);
    collection.find(obj).toArray(function(err, docs) {
        if(err){return callback(err);}
        console.log("Found the following records");
        if(callback!=null){
            callback(err,docs,db);
        }
    });
}

function insertDocumentsByDb(obj ,col, db, callback) {
    var collection = db.collection(col);
    collection.insert(obj, function(err, result) {
        if(err){return callback(err);}
        assert.equal(err, null);
        console.log("Inserted documents into the document collection");
        if(callback!=null){
            callback(err,result,db);
        }
    });
}

function updateDocumentsByDb(queryObj,updateObj ,col, db, callback) {
    var collection = db.collection(col);
    collection.update(queryObj, {$set:updateObj}, function(err, result) {
        if(err){return callback(err);}
        assert.equal(err, null);
        console.log("Inserted documents into the document collection");
        if(callback!=null){
            callback(err,result,db);
        }
    });
}


exports.insertByDb = insertDocumentsByDb;
exports.findByDb = findDocumentsByDb;
exports.updateByDb = updateDocumentsByDb;
exports.connect = connect;
exports.user = user_col;
exports.cookie = cookie_col;
